package es.uji.viselab.robot.links.fanuc;


import java.io.*;
import java.net.*;

import es.uji.viselab.LogLevel;
import es.uji.viselab.LogRecorder;
import es.uji.viselab.robot.RobotAnswer;
import es.uji.viselab.robot.RobotException;


public class RobotCommunicationABBIRB140 {


	   protected Socket socket; 
	   protected BufferedWriter writer; 
	   protected BufferedReader reader;
	   

	   public void connect(String IP, int port) throws RobotException
	   {
		   
			   try {
				 socket = new Socket(IP,port);
		         writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			     reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		       } catch (Exception e) {
		    	 LogRecorder.log(LogLevel.ERROR,"Connection refused.","ABBIRB140.connect();");  
				 throw new RobotException(e.getMessage());	
		       }
			   
		       String answer= send("ping"); 
			   System.out.println("Connect sucessfull, answer: " + answer);
	   }
	   
	   public  String send(String text) throws RobotException{
			   String answer=null;
			   try {
			     writer.write(text,0,text.length());
		         //writer.newLine();
		         writer.flush();
		         answer = reader.readLine();
			   } catch (Exception e) {
				   e.printStackTrace();
				   throw new RobotException(e.getMessage());	 
			   }
		   return answer;
	   }
	   
	   public  RobotAnswer send2(String text) throws RobotException{
		  
	      String answer = send(text);
		  RobotAnswer ra = new RobotAnswer(answer); 
		  return ra;
		  
	   }
	  

	public  void close() throws RobotException{
		   try {
		     writer.close();
		     reader.close();
		     socket.close();
	       } catch (Exception e) {
		     e.printStackTrace();
		     throw new RobotException(e.getMessage());	
	       }
	   }

	public String ping() throws RobotException {
		return send("ping");
	}

	public String disconnect() throws RobotException {
		return send("end");
		
	}

	}	
